package com.kaigejava.listener.confirmlistener;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.QueueingConsumer;

/**
 * Created by kaigejava on 2019/7/21.
 * 消息确认消费端
 */
public class Cosumer4ConfirmListener {
    public static void main(String[] args) throws  Exception {



        //1 创建ConnectionFactory
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("192.168.31.130");
        connectionFactory.setPort(5672);
        connectionFactory.setVirtualHost("/");

        //2 获取C	onnection
        Connection connection = connectionFactory.newConnection();

        //3 通过Connection创建一个新的Channel
        Channel channel = connection.createChannel();

        String exchangeName = "test_confirm_exchange";
        String routingKey = "confirm.#";
        String queueName = "test_confirm_queue";

        //4 声明交换机和队列 然后进行绑定设置, 最后制定路由Key
        channel.exchangeDeclare(exchangeName, "topic", true);
        channel.queueDeclare(queueName, true, false, false, null);
        channel.queueBind(queueName, exchangeName, routingKey);

        //5 创建消费者
        QueueingConsumer queueingConsumer = new QueueingConsumer(channel);
        channel.basicConsume(queueName, true, queueingConsumer);

        while(true){
            QueueingConsumer.Delivery delivery = queueingConsumer.nextDelivery();
            String msg = new String(delivery.getBody());

            System.err.println("消费端: " + msg);
        }
        /*
        //1:创建工厂对象
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setPort(5672);
        connectionFactory.setHost("192.168.31.130");
        connectionFactory.setVirtualHost("/");
        //2：通过工厂对象获取到连接对象
        Connection connection = connectionFactory.newConnection();
        //3:从连接对象中获取到消息通过channel对象
        Channel channel = connection.createChannel();
        String exchangeName = "test_confirm_exchange";
        //我们使用topic模式的时候，可以使用*或#号
        String routingKey = "confirm.*";
        String queueName = "test_queue_confirm";
        // 4.1:设置路由exchange
        channel.exchangeDeclare(exchangeName,"topic",true);
        //4.2：设置队列
        channel.queueDeclare(exchangeName,true,false,false,null);
        // 4.3:设置 路由和队列绑定关系
        channel.queueBind(queueName,exchangeName,routingKey);
        //5:创建消费者
        QueueingConsumer consumer = new QueueingConsumer(channel);
        channel.basicConsume(queueName,true,consumer);
        //获取消息
        while (true){
           QueueingConsumer.Delivery delivery =  consumer.nextDelivery();
           String message = new String (delivery.getBody(),"UTF-8");
            System.out.println("消费端获取到的消息为:"+message);
        }*/

    }
}

